package com.administrator.scoreManageSys.utils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * Excel工具类
 *
 * @author zsh
 * @date 2022/04/07/ 15:31
 */
public class ExportExcelUtil {
    public boolean isLand = true;

    /**
     * 导出EXCEL
     *
     * @param ex       EXCEL 对象
     * @param data     列表数据
     * @param title    附件名称
     * @param headers  表头
     * @param headersL 表头列宽
     * @param fileName 附件名称
     * @param type     默认值 1
     * @param response
     * @throws IOException
     */
    public void exportExcel(ExportExcelList ex, List<Map<String, Object>> data, String title, Map<String, String> headers, Integer[] headersL, String fileName, int type, HttpServletResponse response) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ex.isLand = this.isLand;
            ex.excelExport(data, headers, os, title, headersL, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes("gb2312"), "iso-8859-1"));
        response.setCharacterEncoding("UTF-8");
        //跨域
//        response.setHeader("Access-Control-Allow-Origin","*");
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
    }

}
